package com.lesama.test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.UUID;

public class SubmitFileTask implements Runnable {
    private Socket socket;

    public SubmitFileTask(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            // 3. 获取网络输入输出流
            InputStream is = socket.getInputStream();
            OutputStream os = socket.getOutputStream();

            // 4. 封装成缓冲流
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));

            // 5. 服务器读取客户端传来的文件名
            String filename = br.readLine();
            bw.write("ok"); // 向客户端表示接收成功
            bw.newLine();
            bw.flush();

            // 6. 读取客户端上传的文件， 并存储到本地
            File file = new File("D:\\photo\\temp", UUID.randomUUID() + "-" + filename);
            FileOutputStream fos = new FileOutputStream(file);
            byte[] bytes = new byte[1024];
            int len;
            while((len = is.read(bytes)) != -1) {
                fos.write(bytes, 0, len);
            }
            fos.close();

            // 7. 向客户端传递上传成功的消息
            bw.write("上传成功");
            bw.newLine();
            bw.flush();

            // 8. 关闭相关流
            socket.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}